package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.ChooseProductListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.ProductLedgerOriginal;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by lenovo on 2016/4/21.
 */
public class ChooseProductListFragment extends BaseListFragment {
  protected static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.ChooseProductListFragment.EXTRA_CONTENT";
  private int REQUEST_DETAIL = 0;
  private ChooseProductListAdapter mAdapter;
  private ProductLedgerOriginal.ProductLedgerContent mContent;
  private ArrayList<ProductLedgerOriginal.ProductLedgerContent> mlist;
  private CurrentUser mCurrentUser = CurrentUser.newInstance(getActivity());
  private EditText etproductName;

  @Override public void onCreate(Bundle savedInstanceState) {
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.productList);
    super.onCreate(savedInstanceState);
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_search_person, null, false);
    etproductName = (EditText) header.findViewById(R.id.et_search_searchPersonHeader);
    etproductName.setHint(R.string.productHint);
    etproductName.addTextChangedListener(new MyTextWatcher());
    mListview.addHeaderView(header);
  }

  //    @Override
  //    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  //        inflater.inflate(R.menu.menu_contacts_search, menu);
  //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  //            MenuItem searchItem = menu.findItem(R.id.menu_item_search);
  //            SearchView searchView = (SearchView) searchItem.getActionView();
  //
  //            SearchManager searchManager = (SearchManager) getActivity()
  //                    .getSystemService(Context.SEARCH_SERVICE);
  //            ComponentName name = getActivity().getComponentName();
  //            SearchableInfo searchInfo = searchManager.getSearchableInfo(name);
  //            searchView.setSearchableInfo(searchInfo);
  //            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
  //
  //                @Override
  //                public boolean onQueryTextSubmit(String query) {
  //
  //                    return false;
  //                }
  //
  //                @Override
  //                public boolean onQueryTextChange(String newText) {
  //                    if (mlist == null || mlist.size() == 0) {
  //                        return false;
  //                    }
  //                    if (TextUtils.isEmpty(newText)) {
  //                        setAdapter(mlist);
  //                    } else {
  //                        updateItems(newText);
  //                    }
  //
  //                    return true;
  //                }
  //            });
  //        }
  //
  //        super.onCreateOptionsMenu(menu, inflater);
  //    }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  public void updateItems(String query) {

    // 直接通过中文人名来进行搜索
    ArrayList<ProductLedgerOriginal.ProductLedgerContent> listNames =
        new ArrayList<ProductLedgerOriginal.ProductLedgerContent>();// 获取人名
    String str = "";

    for (int i = 0; i < mlist.size(); i++) {
      str = mlist.get(i).getProductName();
      if (str.contains(query)) {
        listNames.add(mlist.get(i));
      }
    }

    if (listNames.size() == 0) {
      // 弹出提示
      ToastUtil.show(R.string.noProduct);
    }
    //刷新列表
    setAdapter(listNames);
    etproductName.requestFocus();
  }

  @Override public String getUrl() {
    return ApiConst.URL_PRODUCT_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("memberCode", mCurrentUser.getMemberCode().toString());
    params.put("dataStatus", "publish");
    params.put("materialKindCodeLikeStr", "05");
    return params;
  }

  @Override public void resolveResponse(String arg0) {
    ProductLedgerOriginal original = new Gson().fromJson(arg0, ProductLedgerOriginal.class);
    List<ProductLedgerOriginal.ProductLedgerContent> rows = original.getRows();
    if (mlist == null) {
      mlist = new ArrayList<ProductLedgerOriginal.ProductLedgerContent>();
    }
    mlist.clear();
    mlist.addAll(rows);
    setAdapter(mlist);
  }

  private void setAdapter(ArrayList<ProductLedgerOriginal.ProductLedgerContent> mlist2) {
    if (null == mlist) {
      mlist = new ArrayList<ProductLedgerOriginal.ProductLedgerContent>();
    }
    // 将mtasks放入适配器显示
    mAdapter = new ChooseProductListAdapter(getActivity(), mlist2);
    setListAdapter(mAdapter);
    ((ChooseProductListAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    mContent = mAdapter.getItem(position - 2);
    Intent i = new Intent();
    i.putExtra(EXTRA_CONTENT, mContent);
    getActivity().setResult(Activity.RESULT_OK, i);
    getActivity().finish();
    super.onListItemClick(l, v, position, id);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_DETAIL) {

    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  /**
   * 文字监听
   */
  private class MyTextWatcher implements TextWatcher {

    public MyTextWatcher() {
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
      if (mlist == null || mlist.size() == 0) {
        return;
      }
      String query = etproductName.getText().toString().trim();
      if (TextUtils.isEmpty(query)) {
        setAdapter(mlist);
        etproductName.requestFocus();
      } else {
        updateItems(query);
      }
    }

    @Override public void afterTextChanged(Editable editable) {

    }
  }
}
